// src/main/java/beer/xz/beer/device/data/DataLoader.kt
package beer.xz.beer.device.data

import android.annotation.SuppressLint
import android.util.Log
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.platform.LocalContext
import beer.xz.beer.device.data.api.ApiConfig
import beer.xz.beer.device.data.api.Apis
import beer.xz.beer.device.data.channel.Channels
import beer.xz.beer.device.data.product.Products
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext


@SuppressLint("HardwareIds")
@Composable
fun LoadConfig(
    onProgress: (text: String, progress: Float) -> Unit = { _: String, _: Float -> },
    onLoaded: () -> Unit = {},
    onFailed: () -> Unit = {}
) {


//    if (ApiConfig.isLoaded()) {
//        onLoaded()
//    } else {
    val context = LocalContext.current



    LaunchedEffect(key1 = true) {
        var success = true
        try {
            withContext(Dispatchers.IO) {
                ApiConfig.init(context)

                //----------------获取Secret key----------------------
                onProgress("获取设备信息...", 0.1f) // 更新进度到 50%
                // 根据 SN 获取 SecretKey
                val secretKeyResponse =
                    Apis.ControllerSecretKeyService.getSecretKey(ApiConfig.getCode()!!)
                val secretKey = secretKeyResponse.data?.secretKey
                if (secretKey != null) {
                    ApiConfig.replaceSecretKey(secretKey)
                    onProgress("加载设备信息完成", 0.5f) // 更新进度到 50%
                } else {
                    onProgress("设备未注册，请联系管理员", 0.5f) // 更新进度到 50%
                    success = false
                    onFailed()
                }
                //------------获取通道信息--------------------------

                onProgress("获取通道信息...", 0.6f)

                if (Channels.load(context)) {
                    onProgress("加载通道信息完成", 0.8f)
                } else {
                    onProgress("加载通道信息失败", 0.8f)
                    success = false
                }
                //------------获取产品信息--------------------------

                onProgress("获取产品信息...", 0.9f)

                if (Products.load(context)) {
                    onProgress("加载产品信息完成", 1.0f)
                }

//                onProgress("加载完成", 1.0f)
            }
        } catch (e: Exception) {
            // 处理错误
            e.printStackTrace()
            Log.e("LoadConfig", "Error: ${e.message}")
            onProgress("加载失败,请联系管理员", 1f)
            success = false
            onFailed()
        }
        if (success) {
            onLoaded()
        }
    }
}

